var rawType = $('base').attr('rawType');
/**
 * Created by Administrator on 2017/10/12.
 */

(function(){
	
	refreshErTable();
	
	
    var currentData;
    $(document).on('click','button',function(e){
        e.stopPropagation();
        if ($(this).attr('id') == 'btn-undo'){
            commandManager.undo();
        }else if ($(this).attr('id') == 'btn-redo'){
            commandManager.redo();
        }else if ($(this).attr('id') == 'btn-print'){
            paper.print();
        }else if ($(this).attr('id') == 'btn-clear'){
            graph.clear();
        }else if ($(this).attr('id') == 'btn-png'){
            paper.openAsPNG();
        }else if ($(this).attr('id') == 'btn-svg'){
            paper.openAsSVG();
        }else if ($(this).attr('id') == 'btn-search'){

            if(currentData == undefined){
                layer.open({
                    title: '提示',
                    content: '还没有加载对象',
                    shade: 0
                });
            }else {
                layer.open({
                    type:2,
                    content:['/assets/custom/draw/searchTable2.html'],
                    title:'搜索类型',
                    area:['600px','450px']
                })
            }
        }else if ($(this).attr('id') == 'btn-refresh'){
        	refreshErTable();
        }else if ($(this).attr('id') == 'btn-save'){
            e.stopPropagation();
            var json = graph.toJSON();
            console.log(JSON.stringify(json));
            var dataObjectsPosition = new Array();
            $.each(json.cells, function (i, v) {
                if (v.type == 'link') {
                    return;
                }
                var json_position =
                    {
                        "modelId": $("base").attr("modelId"),
                        "objectId": v.id,
                        "positionX": v.position.x,
                        "positionY": v.position.y,
                        "positionWidth": v.size.width,
                        "positionHeight": v.size.height
                    };
                dataObjectsPosition.push(json_position)
            });

            $.ajax({
                url: '/rest/dataModel/savePosition',
                type: 'POST',
                dataType: 'json',
                data: {"posList": JSON.stringify(dataObjectsPosition)},
                success: function (data) {
                    console.log('成功');
                    layer.open({
                        title: '提示'
                        , content: '保存成功',
                        shade: 0
                    });
                },
                error: function (data) {
                    layer.open({
                        title: '提示'
                        , content: '保存失败',
                        shade: 0
                    });
                    console.log('网络异常')
                }
            })
        }else if ($(this).attr('id') == 'btn-layout'){
            $.ajax({
                url : requestUrl+'/rest/webpage/render/fullPosition',
                type: 'POST',
                dataType: 'JSON',
                data : {"dsId":dsId,"modelId":modelId, "rawType":rawType},
                success: function (data) {
                    $.each(data.object.dataObjects,function(i,v){
                        var cell = graph.getCell(v.objectId);

                        cell.position(v.positionVo.positionX,v.positionVo.positionY)  //移动元素的位置
                    })

                },
                error : function(data){
                    console.log(data)
                }
            })
        }
    })
           
    function len(s) {
    	 var l = 0;
    	 var a = s.split("");
    	 for (var i=0;i<a.length;i++) {
    	  if (a[i].charCodeAt(0)<299) {
    	   l++;
    	  } else {
    	   l+=2;
    	  }
    	 }
    	 return l;
    	}
    

    function refreshErTable(){
    	var lodingShade;
    	  $.ajax({
              url : requestUrl+'/rest/webpage/render/full',
              type: 'POST',
              dataType: 'JSON',
              data : {"dsId":dsId,"modelId":modelId, "rawType":rawType},
              beforeSend: function () {
            	  var lodingShade = '<div class="lodingShade" style="position:absolute;top:0;left:0;bottom:0;right:0;background: rgba(0,0,0,.3); z-index: 10;"><div style="position:fixed;left:50%;top:50%;transform: translate(-50%,-50%);padding:12px 25px;background:#fff;border-radius: 3px;"><i class="layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop" style="font-size: 24px;vertical-align: sub;"></i><span style="margin-left:5px;">正在加载中，请耐心等候...</span></div></div>';
            	  $(document.body).append(lodingShade);
              },
              success: function (data) {
                  window.data = currentData = data;
                 
                  var data_list = {'cells': []}; //渲染元素的对象
                  
                  var startTime =new Date().getTime();
                  $.each(data.object.dataObjects, function (i, v) {
    
                      var this_v = v;  //记录当前表对象
                      var objectChname = this_v.objectChname ? this_v.objectChname : this_v.tableName //表中文名
                      var tableName = this_v.tableName?this_v.tableName:this_v.objectChname //表英文名
                    		  
                      var obj =   {
                          "type": "bpmn.Choreography",
                          "participants": [
                                           	objectChname
                          ],
                          "initiatingParticipant": "Potential Buyer",
                          "position": {
                              "x": this_v.positionVo.positionX,
                              "y": this_v.positionVo.positionY
                          },
                          "angle": 0,
                          "id": this_v.objectId,
                          "embeds": "",
                          "z": 1,
                          "qTableName" : this_v.qTableName,
                          "subProcess": false,
                          "attrs": {
                              ".participant-rect": {
                                  "fill": "ff8040"
                              },
                              '.participant-label':{
                                  'fill': '#fff'
                              },
                              ".sub-process": {
                                  "visibility": "hidden",
                                  "data-sub-process": ""
                              },
                              'div': {

                              },
                              '.body' : {

                              },
                              "objectType" : this_v.objectType,
                              'objectChname': objectChname,
                              'tableName': tableName,
                              'isEnglish': false
                          }
                      };
                      
                      var MaxChart;
                      var maxShowNameCharSize = 0;
                      var maxDataTypeCharSize = 0;
                      var maxFeatureCharSize = 0;                      
                      
                      var fieldsArr = [];
                      $.each(this_v.columns, function (i, v) {   //遍历字段信息
                    	  var columnShowname =  v.columnChname ? v.columnChname: v.columnName;
                    	  var columnNameEnglish = v.columnName?v.columnName:v.columnChname;
                    	  var columnDataTypeFullText = v.dataTypeFullText; 
                    	  var columnFeature = "[";
                    	  if (v.pk){
                    		  columnFeature = columnFeature + "PK,";
                    	  }
                    	  if (v.fk){
                    		  columnFeature = columnFeature + "FK,";
                    	  }
                    	  if (v.nk){
                    		  columnFeature = columnFeature + "NK,";
                    	  }
                    	  
                    	  if (columnFeature.charAt(columnFeature.length-1) == ','){
                    		  columnFeature = columnFeature.substring(0, columnFeature.length -1) + "]";
                    	  }
                    	  else {
                    		  columnFeature = "";
                    	  }
                    	  
                    	  var showNameCharSize = len(columnShowname) *7;
                    	  var dataTypeCharSize = len(columnDataTypeFullText) *7;
                    	  var featureCharSize = len(columnFeature) *7;                    	  
                    	 
                    	  if (showNameCharSize > maxShowNameCharSize)  maxShowNameCharSize = showNameCharSize;
                    	  if (dataTypeCharSize > maxDataTypeCharSize)  maxDataTypeCharSize = dataTypeCharSize;
                    	  if (featureCharSize > maxFeatureCharSize)  maxFeatureCharSize = featureCharSize;
                    	
                    	  
                    	  
                        var pfields = '<tr><td class="fieldsTd columnName" data-columnName="' + columnNameEnglish + '" data-columnChname="' +columnShowname+ '">' + columnShowname + '</td><td class="fieldsTd">'+columnDataTypeFullText+'</td><td class="fieldsTd">'+columnFeature+'</td></tr>';
                        fieldsArr.push(pfields);   //每行添加到元素中
                      })
                      
                      MaxChart = maxShowNameCharSize + maxDataTypeCharSize + maxFeatureCharSize;
                      
                      obj.attrs.div.html =  '<table>'+fieldsArr.join("")+'</table>';  //字段信息全部加载到元素中
                      obj.size = {  //元素的大小
                            "width": ((this_v.positionVo.positionWidth && rawType !='fm') ? this_v.positionVo.positionWidth : MaxChart + 100),
                            "height": ((this_v.positionVo.positionHeight && rawType !='fm') ? this_v.positionVo.positionHeight : (30 + (this_v.columns.length>5?5:this_v.columns.length) * 25))
                        }; //字段宽度的最大值
                     

                      data_list.cells.push(obj);      //所有的表对象添加

                  });
                
                  var time1 =new Date().getTime();
                  console.log("复制表对象耗时:" +  (time1 - startTime));                 
                 
                  
                  $.each(data.object.fks, function (i, v) {  //遍历线
                      var link = {
                          "type":"link",
                          "source":{"id":v.objectId},
                          "target":{"id":v.refedObjectId},
                          //  "router":{"name":"manhattan"},
                          "connector":{"name":"rounded"},
                          "id":v.fkId,
                          "z":7,
                          "vertices":[],
                          "attrs":{".connection":{"stroke":"#20C1DD","stroke-width":2,"stroke-dasharray":(v.isPhy?null:"5 2"),"pointerEvents":"none"},
                              ".marker-target":{"fill":"#20C1DD","stroke":"#20C1DD","d":"M 10 0 L 0 5 L 10 10 z"}}
                          ,
                          "labels": [
                              {"position": 0.5, "attrs": {"text": {"text": v.fkChname ? v.fkChname : v.phyFkName}}}
                          ],
                          '.tool-remove' : v.isPhy?null:''
                      };
                      data_list.cells.push(link); //所有的关系对象添加
                  });
               
                  var time2 =new Date().getTime();
                  console.log("复制连线对象耗时:" +  (time2 - time1));
                  
                  graph.fromJSON(data_list);   //导入json数据
                  
                  $(".lodingShade").remove();
                  
                  var endTime =new Date().getTime();
                  console.log("渲染ER图耗时:" +  (endTime - time2));
                  console.log("加载ER图总耗时:" +  (endTime - startTime));
                  
                  if(!$('.joint-type-link').children('.connection').attr('stroke-dasharray')){  //物理线不能关闭
                      $('.joint-type-link').children('.connection').siblings('.link-tools').children().children('.tool-remove').remove();
                  }


                  //双击元素
                  paper.off('cell:pointerdblclick').on('cell:pointerdblclick', function(cellView) {
                      if($(cellView.el).hasClass("joint-type-bpmn")){  //bpmn元素
                      	console.log(cellView.model.attributes.participants[0])
                          layer.open({
                              type: 2,
                              title:cellView.model.attributes.participants[0],
                              content: [requestUrl+'/page/dataObj/index?tableId='+ cellView.model.id],
                              area: ['60%', '50%'],
                              maxmin: true,
                              cancel:function(index,layero){
                                  console.log(currentData);
                                  $.ajax({
                                      url: requestUrl+'/rest/webpage/render/dataObj?objId='+cellView.model.id,
                                      type: 'GET',
                                      dataType: 'json',
                                      data: {},
                                      success: function (data) {
                                    	  console.log(data)
                                    	 
                                          $(cellView.el).find('tspan').text(data.objectChname ? data.objectChname : data.tableName); //修改表的标题

                                          var fieldsArr = [];
                                          $.each(data.columns, function (i, v) {
                                         /*     var isK;
                                              if (v.pk == true) {
                                                  isK = '[PK]';
                                              } else if (v.fk == true) {
                                                  isK = '[FK]';
                                              } else if (v.nk == true) {
                                                  isK = '[NK]';
                                              } else {
                                                  isK = '';
                                              }*/
                                              
                                              var columnFeature = "[";
                                        	  if (v.pk){
                                        		  columnFeature = columnFeature + "PK,";
                                        	  }
                                        	  if (v.fk){
                                        		  columnFeature = columnFeature + "FK,";
                                        	  }
                                        	  if (v.nk){
                                        		  columnFeature = columnFeature + "NK,";
                                        	  }
                                        	  
                                        	  if (columnFeature.charAt(columnFeature.length-1) == ','){
                                        		  columnFeature = columnFeature.substring(0, columnFeature.length -1) + "]";
                                        	  }
                                        	  else {
                                        		  columnFeature = "";
                                        	  }

                                              var pfields = '<tr><td class="fieldsTd">'+(v.columnChname ? v.columnChname.replace(/\s/g, '') : v.columnName)+'</td><td class="fieldsTd">'+v.dataTypeFullText+'</td><td>'+columnFeature+'</td></tr>';
                                              fieldsArr.push(pfields);
                                          });

                                          var tableStr = '<table>'+fieldsArr.join('') +'</table>';
                                          $(cellView.el).find('.content').html(tableStr);   //修改view中表的content
                                          var ins = new joint.ui.Inspector({
                                              cellView:cellView.model,
                                          });
                                          ins.options.cellView.attributes.attrs.div.html = tableStr;  //修改model中表的content
                                      },
                                      error: function (data) {
                                          console.log(data)
                                      }
                                  });

                              }
                          });
                      }
                  });


              },
              error: function (data) {

            	  $(".lodingShade").remove();
                  layer.open({
                      title: '提示',
                      content: '网络异常',
                      shade: 0
                  });
                  console.log('网络异常')
              }
          })
    }

})();








